package com.inspur.gs.sbssdl.sbwhgl.gyjgl.gyjgl.back.gyjtz.determinations;
import com.inspur.edp.bef.api.lcp.ILcpFactory;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.api.services.IBefSessionManager;
import com.inspur.edp.cef.api.message.*;
import com.inspur.edp.bef.api.action.determination.*;
import com.inspur.edp.bef.spi.action.determination.*;
import com.inspur.edp.cef.entity.changeset.*;
import com.inspur.edp.bef.spi.action.determination.AbstractDetermination;
import com.inspur.edp.bef.api.action.determination.IDeterminationContext;
import com.inspur.edp.cef.entity.condition.*;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.bef.api.action.determination.IBeforeRetrieveDtmContext;
import com.inspur.edp.cef.entity.entity.IValuesContainer;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class gyjtzsaveBeofreCodeMgrAction extends AbstractB4SaveDetermination {
	public gyjtzsaveBeofreCodeMgrAction(IDeterminationContext context, IChangeDetail change) {
		super(context,change);
	}
	@Override
	public  void execute() {
		IEntityData currentData = this.getContext().getCurrentData();
		String lx = (String) ((IValuesContainer) currentData.getValue("lx")).getValue("lx");
		String lxbh = (String) ((IValuesContainer) currentData.getValue("lx")).getValue("lx_lxbh");
		SpringBeanUtils.getBean(IBefSessionManager.class).createSession();
		try {
			//点检配置变更
			ILcpFactory iLcpFactory = SpringBeanUtils.getBean(ILcpFactory.class);
			String gyjtzid = "46911fe3-0d25-4e16-9e9e-c93393525ced";
			IStandardLcp gyjtzlcp = iLcpFactory.createLcpByBEId(gyjtzid);

			EntityFilter filter = new EntityFilter();
			FilterCondition condition = new FilterCondition(0,"lx", ExpressCompareType.Equal, lx, 0, ExpressRelationType.Empty, ExpressValueType.Value);
			ArrayList<FilterCondition> list=new ArrayList<>();
			list.add(condition);
			filter.setFilterConditions(list);
			List<IEntityData> tzdata = gyjtzlcp.query(filter);

			String debh = (tzdata == null || tzdata.isEmpty())
					? lxbh + "-1001"  // 如果 tzdata 为空，直接生成默认值
					: tzdata.stream()
					.map(s -> (String) s.getValue("debh"))
					.filter(Objects::nonNull)
					.filter(s -> s.length() >= 4)
					.max(Comparator.comparing(s -> s.substring(s.length() - 4)))
					.map(maxDebh -> {
						// 如果找到最大值，计算后四位+1
						String last4Str = maxDebh.substring(maxDebh.length() - 4);
						int last4Num = Integer.parseInt(last4Str) + 1;
						return maxDebh.substring(0, maxDebh.length() - 4) + String.format("%04d", last4Num);
					})
					.orElse(lxbh + "-1001");  // 如果没有有效数据，返回默认值

			currentData.setValue("debh",debh);

		} finally {
			SpringBeanUtils.getBean(IBefSessionManager.class).closeCurrentSession();
		}
	}
	private IEntityData getData() {
		return (IEntityData)super.getContext().getCurrentData();
	}
}